import platform
import socket
import uuid
import subprocess
import re


class DeviceInfo:
    def __init__(self):
        self.info = self.collect_info()

    def get_mac_address(self):
        """获取MAC地址（跨平台支持）"""
        try:
            mac = uuid.getnode()
            return ':'.join(['{:02x}'.format((mac >> elements) & 0xff)
                             for elements in range(0, 8 * 6, 8)][::-1])
        except:
            return "Unknown"

    def get_ip_address(self):
        """获取IP地址（跨平台支持）"""
        try:
            # 创建一个UDP连接来获取本地IP，不需要实际建立连接
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            return socket.gethostbyname(socket.gethostname())

    def get_os_info(self):
        """获取操作系统信息（跨平台支持）"""
        system = platform.system()
        if system == "Darwin":
            # macOS
            try:
                os_version = subprocess.check_output(['sw_vers', '-productVersion']).decode().strip()
                return "macOS", os_version
            except:
                return "macOS", platform.release()
        elif system == "Linux":
            # Linux
            try:
                # 尝试读取发行版信息
                with open('/etc/os-release') as f:
                    lines = f.readlines()
                    name = next((l for l in lines if l.startswith('NAME=')), 'Linux')
                    version = next((l for l in lines if l.startswith('VERSION_ID=')), '')
                    name = re.search(r'NAME="(.+)"', name)
                    version = re.search(r'VERSION_ID="(.+)"', version)
                    return (name.group(1) if name else "Linux",
                            version.group(1) if version else platform.release())
            except:
                return "Linux", platform.release()
        else:
            # Windows
            return "Windows", platform.release()

    def collect_info(self):
        """收集设备信息"""
        try:
            os_name, os_version = self.get_os_info()
            info = {
                "device_name": socket.gethostname(),
                "os_name": "{} {}".format(os_name,os_version),
                "ip_address": self.get_ip_address(),
                "mac_address": self.get_mac_address()
            }
            return info
        except Exception as e:
            print(f"收集信息时出错: {str(e)}")
            return {}

    def print_info(self):
        """打印设备信息"""
        print("\n=== 设备信息 ===")
        for key, value in self.info.items():
            print(f"{key}: {value}")
        print("==============")

    def get_info(self):
        """返回设备信息字典
        设备名称: zhangyuanlong-
        操作系统: Windows
        系统版本: 11
        IP地址: 192.168.110.87
        MAC地址: 74:04:f1:66:1d:12

        """
        return self.info


# 使用示例
if __name__ == "__main__":
    device = DeviceInfo()
    device.print_info()
